<template>
  <!-- 任务列表 -->
  <div class="mymissions-container">
    <div class="overview-wrapper">
      <div class="budget">
        <span>Budget:</span>
        <span>$ {{ balance }}</span>
      </div>
      <div class="order">
        <span>Order:</span>
        <span>{{ orderCount }}</span>
      </div>
    </div>
    <cube-tab-bar v-model="selectedTab" show-slider>
      <cube-tab v-for="(item, i) in tabs" :label="item.label" :key="item.label"></cube-tab>
    </cube-tab-bar>

    <div class="scroll-view">
      <cube-tab-panels v-model="selectedTab">
        <cube-tab-panel v-for="(item, i) in tabs" :label="item.label" :key="item.label">
          <ul class="tab-panel-list">
            <li class="tab-panel-li card" v-for="(mission, i) in item.missionList">
              <!-- mission.orderImg ? mission.orderImgArr[0] : -->
              <div class="image-wrapper" @click="onMissionDetail(mission)">
                <img :src="mission.productImg" alt />
              </div>
              <div class="info-wrapper">
                <div
                  class="item-name ellipsis"
                  @click="onMissionDetail(mission)"
                >{{ mission.titleEnglish }}</div>
                <div class="item-profit" @click="onMissionDetail(mission)">
                  <div class="price">
                    <span class="title-color">Price: $</span>

                    {{ mission.price }}
                    <!-- <span>orderId: {{mission.orderId}}</span> -->
                  </div>
                  <div class="reward">
                    <span class="title-color">Reward: $</span>
                    {{ mission.commission ? mission.commission.toFixed(2) : ''}}
                  </div>
                </div>
                <div class="item-actions text-right">
                  <cube-button
                    outline
                    v-if="mission.orderStatus === 1"
                    @click="onCancelMission(item.label, mission)"
                  >Cancel</cube-button>

                  <cube-button
                    outline
                    @click="onOrderUpload(item.label, mission)"
                    v-if="mission.orderStatus === 1"
                  >Order Upload</cube-button>

                  <cube-button
                    outline
                    @click="onReviewUpload(item.label, mission)"
                    v-if="mission.orderStatus === 4 && mission.taskType !== 1"
                  >Review Upload</cube-button>
                </div>
              </div>
            </li>
          </ul>
        </cube-tab-panel>
      </cube-tab-panels>
    </div>

    <div class="dialog-wrapper" v-if="dialog">
      <div class="upload-wrapper elevation-2">
        <div class="close-wrapper">
          <span @click.stop="dialog = false">
            <i class="fa fa-times-circle fa-lg icon"></i>
          </span>
        </div>
        <div class="input-wrapper" v-if="dialogItem.orderStatus === 1">
          <input ref="orderInput" type="file" accept="image/*" @change="onOrderFileChange" />
          <img class="preview-image" :src="orderImagePreview" alt v-if="orderImagePreview !== ''" />

          <i v-if="orderImagePreview === ''" class="fa fa-cloud-upload fa-lg icon"></i>

          <div v-if="orderImagePreview === ''" class="upload-tip title-color">Choose order image</div>
        </div>

        <div class="input-wrapper" v-if="dialogItem.orderStatus === 4">
          <input ref="reviewInput" type="file" accept="image/*" @change="onReviewFileChange" />
          <img class="preview-image" :src="reviewImagePreview" alt v-if="reviewImagePreview !== ''" />

          <i v-if="reviewImagePreview === ''" class="fa fa-cloud-upload fa-lg icon"></i>

          <div v-if="reviewImagePreview === ''" class="upload-tip title-color">Choose review image</div>
        </div>

        <div class="dialog-actions">
          <div class="confirm" @click="onDialogConfirm">Confirm</div>
          <div class="cancel" @click="onDialogCancel">Cancel</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { Api, FileHandler, Login } from "@/api";
import { RespFileVo } from "@/api/bean";
import Cookie from "js-cookie";

@Component({
  components: {}
})
export default class MyMissions extends Vue {
  private selectedTab: string = "New Order";
  private dialog: boolean = false;
  private dialogItem: any = {};
  private get orderCount() {
    let o1 = this.tabs[0].missionList ? this.tabs[0].missionList.length : 0;
    let o2 = this.tabs[1].missionList ? this.tabs[1].missionList.length : 0;
    let o3 = this.tabs[2].missionList ? this.tabs[2].missionList.length : 0;

    return o1 + o2 + o3;
  }
  private balance: number = 0;

  private tabs = [
    {
      label: "New Order",
      icon: "cubeic-like",
      missionList: [
        // {
        //   imageUrl:
        //     "http://img0.imgtn.bdimg.com/it/u=311307345,3690847989&fm=11&gp=0.jpg",
        //   itemName: "Filco Keyboard II Red",
        //   price: 25.8,
        //   reward: 25.8,
        //   status: 1
        // },
      ]
    },
    {
      label: "In Process",
      icon: "cubeic-star",
      missionList: [
        // {
        //   imageUrl:
        //     "http://img0.imgtn.bdimg.com/it/u=311307345,3690847989&fm=11&gp=0.jpg",
        //   itemName: "Filco Keyboard II Red",
        //   price: 25.8,
        //   commission: 25.8,
        //   status: 1
        // }
      ]
    },
    {
      label: "Orders 100 Days",
      icon: "cubeic-star",
      missionList: [
        // {
        //   imageUrl:
        //     "http://img0.imgtn.bdimg.com/it/u=311307345,3690847989&fm=11&gp=0.jpg",
        //   itemName: "Filco Keyboard II Red",
        //   price: 25.8,
        //   commission: 25.8,
        //   status: 1
        // }
      ]
    }
  ];

  private orderImagePreview: string = "";
  private reviewImagePreview: string = "";

  private orderImage: any = null;
  private reviewImage: any = null;

  private modalItem: any = {};

  private orderImageUrl: string = "";
  private reviewImageUrl: string = "";

  private dialogType: number = 1;

  protected mounted() {
    this.getData();
  }

  private getData() {
    this.getMyMissionList("newOrder");
    this.getMyMissionList("inProcess");
    this.getMyMissionList("100days");
  }

  private onCancelMission(label: string, mission: any) {
    this.modalItem = mission;
    this.$createDialog({
      type: "confirm",
      icon: "cubeic-alert",
      title: "Attention",
      content: "Confirm to cancel order?",
      confirmBtn: {
        text: "Confirm",
        active: true,
        href: "javascript:;"
      },
      cancelBtn: {
        text: "Cancel",
        active: false,
        href: "javascript:;"
      },
      onConfirm: () => {
        this.cancelMyMission();
      },
      onCancel: () => {}
    }).show();
  }

  private onMissionDetail(data: any) {
    this.$router.push({
      name: "MissionDetail",
      params: data
    });
    sessionStorage.setItem("MissionDetail", JSON.stringify(data));
  }

  /**
   * 提交订单
   */
  private onOrderUpload(label: string, mission: any) {
    this.dialog = true;
    this.dialogItem = mission;
    this.dialogType = 1;
  }

  /**
   * 提交评价
   */
  private onReviewUpload(label: string, mission: any) {
    this.dialog = true;
    this.dialogItem = mission;
    this.dialogType = 2;
  }

  private onOrderFileChange(ev: any) {
    let file = ev.target.files[0];
    this.orderImage = file;
    this.handleImageFile(file, "order");
  }

  private onReviewFileChange(ev: any) {
    let file = ev.target.files[0];
    this.reviewImage = file;
    this.handleImageFile(file, "review");
  }

  private handleImageFile(file: File, type: string) {
    const reader = new FileReader();
    // 使用base64上传
    reader.onload = (ev: any) => {
      if (type === "order") {
        this.orderImagePreview = ev.target.result;
      } else {
        this.reviewImagePreview = ev.target.result;
      }
    };
    reader.readAsDataURL(file);
  }

  /**
   * 处理任务列表显示
   */
  private handleMissionList(list: Array<any>) {
    let list1: Array<any> = [];
    let list2: Array<any> = [];
    let list3: Array<any> = [];
    list.forEach((item: any) => {
      let orderImg = null;
      item.orderImgArr = [];
      if (item.orderImg) {
        if (item.orderImg.match(/\[/g)) {
          try {
            orderImg = JSON.parse(item.orderImg);
            item.orderImgArr = orderImg;
          } catch (err) {
            item.orderImgArr = [item.orderImg];
            console.error(err);
          }
        } else {
          item.orderImgArr = [item.orderImg];
        }
      }

      // 新订单
      if (item.orderStatus === 1) {
        list1.push(item);
      }
      // 正在进行中
      if (item.orderStatus >= 3 && item.orderStatus <= 5) {
        list2.push(item);
      }
      // 已完成
      if (item.orderStatus >= 6 || item.orderStatus === -1) {
        list3.push(item);
      }
    });
    // this.tabs[0].missionList = list1;
    // this.tabs[1].missionList = list2;
    // this.tabs[2].missionList = list3;
  }

  private onDialogConfirm() {
    if (this.dialogType === 1) {
      this.uploadFile(this.orderImage, "order");
    } else if (this.dialogType === 2) {
      this.uploadFile(this.reviewImage, "review");
    }

    // if (this.orderImage === null || this.reviewImage === null) {
    // return this.$createToast({
    //   txt: "You need to choose both images to upload",
    //   type: "Error",
    //   time: 3000
    // }).show();
    // } else {
    // this.uploadFile(this.orderImage, "order");
    // }
  }

  private onDialogCancel() {
    this.dialog = false;
    this.orderImagePreview = "";
    this.orderImage = null;
    this.reviewImagePreview = "";
    this.reviewImage = null;
  }

  private handleFileUploaded(data: RespFileVo, type: string) {
    if (type === "order") {
      this.orderImageUrl = data.fileUrl;
      this.placeOrder(data.fileUrl);
    } else {
      this.reviewImageUrl = data.fileUrl;
      this.saveReview(data.fileUrl, this.dialogItem.orderImg);
    }
  }
  /**
   * 保存文件
   */
  private async uploadFile(file: File, type: string) {
    const params: FormData = new FormData();
    params.append("file", file);
    const { data } = await FileHandler.uploadFile.r(params);
    console.log("uploadFile", data);
    if (data.result === 0) {
      this.handleFileUploaded(data.data[0], type);
    } else {
    }
  }

  /**
   * 下订单 卖家上传订单截图
   */
  private async placeOrder(img: string) {
    const params: any = {
      orderId: this.dialogItem.orderId,
      orderNumber: this.dialogItem.orderNumber,
      img: JSON.stringify([img])
    };
    const { data } = await Api.placeOrder.r(params);
    console.log("placeOrder", data);
    this.getData();
    if (data.result === 0) {
      // this.saveReview(this.reviewImageUrl);
      this.$createToast({
        txt: "Successfully uploaded",
        type: "correct",
        time: 3000
      }).show();
      // this.getMyMissionList();
    } else {
    }
  }

  /**
   * 保存评价 买家上传评价截图
   */
  private async saveReview(img: string, orderImg: string) {
    let orderImgArr = [];

    if (orderImg) {
      orderImgArr = JSON.parse(orderImg);
    }

    let imgArr: any = Array.isArray(img) ? img : [img, orderImgArr[0]];
    const params: any = {
      orderId: this.dialogItem.orderId,
      orderNumber: this.dialogItem.orderNumber,
      img: JSON.stringify(imgArr)
    };
    const { data } = await Api.saveReview.r(params);
    console.log("saveReview", data);
    if (data.result === 0) {
      this.$createToast({
        txt: "Successfully uploaded",
        type: "correct",
        time: 3000
      }).show();
      // this.getMyMissionList();
      this.getData();
    } else {
      this.$createToast({
        txt: data.message,
        type: "warn",
        time: 3000
      }).show();
    }
  }

  /**
   * 获取我的任务列表
   */
  private async getMyMissionList(type: string) {
    let params: any = {
      limit: 1000,
      offset: 0,
      buyerUserId: Number(Cookie.get("buyer_userId"))
    };
    let orderStatusArr = [];
    if (type === "newOrder") {
      params.orderStatusArr = [1];
    }
    if (type === "inProcess") {
      params.orderStatusArr = [3, 4, 5];
    }
    if (type === "100days") {
      params.endTime = new Date().getTime();
      params.beginTime = new Date().getTime() - 100 * 24 * 60 * 60 * 1000;
      params.orderStatusArr = [-1, 6];
    }
    this.dialog = false;
    const { data } = await Api.getOrderList.r(params);
    console.log("getOrderList", data);
    if (data.result === 0) {
      // this.orderCount = data.data.totalCount;
      // this.handleMissionList(data.data.dataList);
      let list: any = data.data.dataList;
      list.forEach((item: any) => {
        let orderImg = null;
        item.orderImgArr = [];
        if (item.orderImg) {
          if (item.orderImg.match(/\[/g)) {
            try {
              orderImg = JSON.parse(item.orderImg);
              item.orderImgArr = orderImg;
            } catch (err) {
              item.orderImgArr = [item.orderImg];
            }
          } else {
            item.orderImgArr = [item.orderImg];
          }
        }
      });
      if (type === "newOrder") {
        this.tabs[0].missionList = list;
      }
      if (type === "inProcess") {
        this.tabs[1].missionList = list;
        // console.log(this.tabs[1].missionList, list);
      }
      if (type === "100days") {
        this.tabs[2].missionList = list;
      }
      // this.getMyMissionList();
    } else {
      this.$createToast({
        txt: data.message,
        type: "warn",
        time: 3000
      }).show();
    }
  }

  /**
   * 取消已有订单
   */
  private async cancelMyMission() {
    const params: any = {
      orderId: this.modalItem.orderId
    };
    const { data } = await Api.invalidOrder.r(params);
    console.log("invalidOrder", data);
    this.$createToast({
      txt: data.message,
      type: "correct",
      time: 3000
    }).show();
    if (data.result === 0) {
      // this.getMyMissionList();
      this.getData();
    } else {
    }
  }

  private async getUserInfo() {
    const params: any = {
      userId: Cookie.get("buyer_userId")
    };
    const { data } = await Login.getUserBalance.r();
    console.log("getSingleUserInfo", data);
    if (data.result === 0) {
      this.balance = data.data;
    } else {
      this.$createToast({
        txt: data.message,
        type: "warn",
        time: 3000
      }).show();
    }
  }
}
</script>

<style lang="less" scoped>
@import url(../../styles/variables.less);
.mymissions-container {
  width: 100%;
  height: 100%;
  position: relative;
  .overview-wrapper {
    height: 2rem;
    width: 100%;
    color: white;
    background-color: @primary;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 1.2rem;
    box-sizing: border-box;
  }
  .tab-panel-list {
    width: 100%;
    padding: 2px 0.4rem;
    box-sizing: border-box;
    .tab-panel-li {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0.6rem 0.3rem;
      margin-bottom: 0.2rem;
      border: 0.8px solid #efefef;
      border-radius: 8px;
      margin-bottom: 0.4rem;
      .image-wrapper {
        flex-basis: 20%;
        width: 20%;
        img {
          max-width: 3rem;
          max-height: 3rem;
        }
      }
      .info-wrapper {
        flex-basis: 80%;
        width: 80%;
        display: flex;
        flex-direction: column;
        padding-left: 8px;
        box-sizing: border-box;
        .item-name {
          width: 84%;
          font-size: 1.1rem;
          height: 1.2rem;
          line-height: 1.2rem;
          text-align: left;
        }
      }
      .item-profit {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        padding: 4px 0;
      }
      .item-actions {
        display: flex;
        justify-content: flex-end;
        .cube-btn {
          width: auto;
          height: 1.5rem;
          padding: 1px 6px;
          font-size: 0.9rem;
          margin-right: 6px;
        }
      }
    }
  }

  .cube-tab {
    padding: 0.6rem 0;
    font-size: 14px;
  }
  // .cube-tab-panels {
  //   height: 100%;
  //   overflow-x: hidden;
  //   overflow-y: auto;
  // }
  .scroll-view {
    height: calc(100% - 6rem);
    overflow-x: hidden;
    overflow-y: auto;
  }

  .dialog-wrapper {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.2);
    z-index: 1;
    .upload-wrapper {
      position: relative;
      width: 80%;
      height: 80%;
      background: white;
      border-radius: 1rem;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      padding: 1rem;
      box-sizing: border-box;
      .close-wrapper {
        text-align: right;
        width: 100%;
        .icon {
          color: #f44336;
        }
      }
      .input-wrapper {
        position: relative;
        width: 90%;
        height: 80%;
        border: 1px dashed #ddd;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 1rem;
        border-radius: 1rem;
        flex-direction: column;
        .preview-image {
          width: 90%;
        }
        .icon {
          color: #888;
          font-size: 2rem;
        }
        input {
          position: absolute;
          width: 100%;
          height: 100%;
          top: 0;
          left: 0;
          opacity: 0;
        }
        div {
          margin-top: 1.2rem;
        }
      }
    }

    .dialog-actions {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      > div {
        flex-basis: 50%;
        width: 50%;
        height: 2rem;
        line-height: 2rem;
      }

      .confirm {
        color: #fa991a;
      }
    }
  }
}

.list {
  width: 375px;
  max-width: 100%;
  height: 100%;
  margin: 0 auto;
  padding: 0;
  border: 1px solid #ddd;
  list-style-type: none;
  text-align: center;
  .item {
    display: flex;
    padding: 10px 0;
    width: 100%;
    text-align: left;
  }
  .avatar {
    border-radius: 50%;
    margin-left: 15px;
    margin-right: 6px;
    min-width: 48px;
    width: 48px;
    height: 48px;
    background-size: cover;
    outline: none;
  }
  p {
    margin: 0;
    word-wrap: break-word;
    font-size: 14px;
  }
  &.tombstone p {
    width: 100%;
    height: 0.5em;
    background-color: #ccc;
    margin: 0.5em 0;
  }
  .bubble {
    padding: 7px 10px;
    color: #333;
    background: #fff;
    box-shadow: 0 3px 2px rgba(0, 0, 0, 0.1);
    position: relative;
    max-width: 420px;
    min-width: 80px;
    margin: 0 20px 0 5px;
  }
  &:before {
    content: "";
    border-style: solid;
    border-width: 0 10px 10px 0;
    position: absolute;
    top: 0;
    left: -10px;
  }
  .meta {
    font-size: 0.8rem;
    color: #999;
    margin-top: 3px;
  }
}
</style>
